import { app, shell, BrowserWindow, ipcMain, Tray, Menu } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
interface WindowDescriptor {
  id: number
  route: string
  content: BrowserWindow
}
type WindowDescriptorArray = WindowDescriptor[]
const group: WindowDescriptorArray = []
let tray
function createWindow(): void {
  const mainWindow = new BrowserWindow({
    icon,
    width: 800,
    height: 600,
    minWidth: 800,
    minHeight: 600,
    show: false,
    frame: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: true // 启用 Node.js 集成（如果需要）
    }
  })

  tray = new Tray(icon)
  tray.setToolTip('猴哥')

  tray.on('click', () => {
    //点击图标的响应事件，这里是切换主窗口的显示和隐藏
    if (mainWindow.isVisible()) {
      mainWindow.hide()
    } else {
      mainWindow.show()
    }
  })

  tray.on('right-click', () => {
    //右键点击图标时，出现的菜单，通过Menu.buildFromTemplate定制，这里只包含退出程序的选项。
    const menu = [
      {
        label: '退出',
        click: (): void => app.quit()
      }
    ]
    if (mainWindow.isVisible()) {
      menu.unshift({
        label: '最小化',
        click: () => mainWindow.hide()
      })
    }
    const menuConfig = Menu.buildFromTemplate(menu)
    tray.popUpContextMenu(menuConfig)
  })

  group.push({
    id: mainWindow.id,
    route: 'main',
    content: mainWindow
  })
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  // 4.开启新窗口
  ipcMain.on(`openWin`, function (e, item) {
    console.log(e, item, '--')

    openChildWindow(item, mainWindow)
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.whenReady().then(() => {
    electronApp.setAppUserModelId('com.electron')

    app.on('browser-window-created', (_, window) => {
      optimizer.watchWindowShortcuts(window)
    })
    // 1. 窗口 最小化
    ipcMain.on(`minWindow`, function (e, url) {
      console.log(e, url, '-----')

      const index = group.findIndex((i) => i.route == url)
      group[index].content.minimize()
    })

    // 2. 窗口 最大化、恢复
    ipcMain.on(`scaleWindow`, function (e, url) {
      console.log(e, url, '--')

      const index = group.findIndex((i) => i.route == url)
      if (group[index].content.isMaximized()) {
        // 为true表示窗口已最大化
        group[index].content.restore() // 将窗口恢复为之前的状态.
      } else {
        group[index].content.maximize()
      }
    })

    // 3. 关闭窗口
    ipcMain.on(`closeWindow`, function (e, url) {
      console.log(e, url, '--')

      const index = group.findIndex((i) => i.route == url)
      if (url === 'main') return group[index].content.hide()
      group[index].content.close()
      group.splice(index, 1)
    })

    // IPC test
    ipcMain.on('ping', () => console.log('pong'))

    createWindow()

    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })

    // 监听第二个实例事件
    app.on('second-instance', () => {
      // 当第二个实例尝试启动时，聚焦到第一个实例的窗口
      if (BrowserWindow.getAllWindows().length > 0) {
        BrowserWindow.getAllWindows()[0].show()
      }
    })
  })
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

const openChildWindow = (param, parent): void => {
  const child = group.find((i) => i.route === param.url)
  if (child) return child.content.show()
  const childWin = new BrowserWindow({
    width: param.width || 600,
    height: param.height || 500,
    parent, // win是主窗口，不加parent，新建的窗口将于主窗口平级
    frame: false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: true // 启用 Node.js 集成（如果需要）
    }
  })
  group.push({
    id: childWin.id,
    route: param.url,
    content: childWin
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    childWin.loadURL(process.env['ELECTRON_RENDERER_URL'] + '#' + param.url)
    childWin.webContents.openDevTools()
  } else {
    childWin.loadFile(join(__dirname, '../renderer/index.html'), { hash: `/${param.url}` })
  }
}
